﻿using ReferToFriend.Dapper;
using ReferToFriend.Models;
using ReferToFriend.Reponsitory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ReferToFriend.Controllers
{
    public class HomeController : Controller
    {
        private DataReponsitory _repository = new DataReponsitory();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult AddRecord(ReferFriend model)
        {
            try
            {
                model.ReferDate = DateTime.Now;

                if (!ModelState.IsValid)
                {
                    var errorModel =
                    from x in ModelState.Keys
                    where ModelState[x].Errors.Count > 0
                    select new ViewErrors
                    {
                        FieldName = x,
                        Errors = ModelState[x].Errors.
                                               Select(y => y.ErrorMessage).ToList()
                    };

                    return Json(new JsonResultViewModel() { Success = false, FieldErrors = errorModel.ToList() });
                   
                }

                var result = _repository.AddRecord(model);
                return Json(new JsonResultViewModel() { Success = true });
            }
            catch (Exception ex)
            {
                return Json(new JsonResultViewModel() { Success = false, Message = ex.Message });
            }
        }
    }
}